<?php

namespace App\Models;

use App\Models\Posts\WxPost;
use App\Models\System\ChinaArea;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\TenantUtils;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class WxTenant extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'wx_tenants';

    protected $primaryKey = 'tenant_id';

    public $incrementing = false;


    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            // 在模型创建之前触发的操作
        });

        static::created(function ($model) {

        });

        static::updating(function ($model) {
            // 在模型更新之前触发的操作
            $model->original = $model->getOriginal();
        });

        static::updated(function ($model) {
            $original = $model->original;
            $changes = $model->getChanges();

            // 对比更新前后的字段
            foreach ($changes as $key => $value) {
                if($key == 'name' || $key == 'logo' || $key == 'short'){
                    WxPost::withoutSyncingToSearch(function () use (&$model){
                        WxPost::where('tenant_id', $model->tenant_id)->update(['tenant_obj'=>null]);
                    });
                }else if($key == 'tenant_id'){
                    $old_tenant_id = $original['tenant_id'] ?? 0;
                    WxPost::where('tenant_id', $old_tenant_id)->update(['tenant_obj'=>null, 'tenant_id'=>$model->tenant_id]);
                    TenantUtils::tenant_change_id_all_tables($old_tenant_id, $model->tenant_id);
                }else if($key == 'add_city'){
                    if(env('APP_IS_MULTI_SITE', 0) > 0){
                        $city_name = ChinaArea::where('code', $model->add_city)->value('name');
                        if($city_name){
                            if(StrUtils::endsWith($city_name, '市')){
                                $city_name = str_replace('市', '', $city_name);
                            }
                            if(StrUtils::endsWith($city_name, '自治区')){
                                $city_name = str_replace('自治区', '', $city_name);
                            }
                            if(StrUtils::endsWith($city_name, '自治州')){
                                $city_name = str_replace('自治州', '', $city_name);
                            }
                            if(StrUtils::endsWith($city_name, '盟')){
                                $city_name = str_replace('盟', '', $city_name);
                            }
                            if(StrUtils::endsWith($city_name, '直辖市')){
                                $city_name = str_replace('直辖市', '', $city_name);
                            }
                            if($city_name != '市辖区'){
                                \App\Models\WxTenant::where('tenant_id', $model->tenant_id)->update(['city' => $city_name]);
                            }else{
                                \App\Models\WxTenant::where('tenant_id', $model->tenant_id)->update(['city' => '']);
                            }
                        }
                    }
                }
            }
        });

        static::deleting(function ($user) {

        });

        static::deleted(function ($player) {

        });
        // 其他的模型事件监听...
    }


    // 添加一个查询作用域，来计算给定经纬度与tenant之间的距离，并按距离排序
    public function scopeNearestByLocation($query, $latitude, $longitude)
    {
        // 地球半径换算成米
        $earthRadius = 6371000;

        return $query->select('*', DB::raw("($earthRadius * acos(cos(radians($latitude))
            * cos(radians(add_latitude))
            * cos(radians(add_longitude) - radians($longitude))
            + sin(radians($latitude)) * sin(radians(add_latitude)))) AS distance"))
            ->orderBy('distance', 'asc');
    }

}
